<template>
	<div class="zs-table-page-container">
		<div class="zs-card-sm zs-space-bottom zs-layout-flex-row zs-layout-justify-between">
			<span>
				<el-input v-model="projectName" class="zs-select-md zs-space-right-sm" placeholder=" " disabled />
				<el-select v-model="queryParams.inspectionType" class="zs-select-md zs-space-right-sm" placeholder="巡检类型" @change="queryList" clearable>
					<el-option v-for="item in standradTypeList" :key="item.id" :label="item.dicName" :value="item.id" />
				</el-select>
				<el-input v-model="queryParams.routeName" class="zs-select-md zs-space-right-sm" placeholder="路线名称" clearable filterable @blur="queryList" />
				<!-- <el-select v-model="queryParams.processKeys" collapse-tags collapse-tags-tooltip class="zs-select-md zs-space-right-sm" placeholder="流程名称" multiple clearable filterable>
					<el-option v-for="item in processList" :key="item.processKey" :label="item.optionName" :value="item.processKey" />
				</el-select> -->
				<el-popover popper-class="zs-popper" placement="bottom-end" trigger="click">
					<template #reference>
						<el-button class="zs-btn-square-solid" :class="{ 'zs-btn-square-solid-active': queryParams.roleKey || queryParams.mandatorySequence || queryParams.inspectionStatus || queryParams.effectiveState }">
							<el-icon>
								<MoreFilled />
							</el-icon>
						</el-button>
					</template>
					<template #default>
						<el-select v-model="queryParams.roleKey" class="zs-select-md zs-space-right-sm" placeholder="角色名称" clearable filterable @change="queryList">
							<el-option v-for="item in roleList" :key="item.roleKey" :label="item.roleName" :value="item.roleKey" />
						</el-select>
						<el-select v-model="queryParams.mandatorySequence" class="zs-select-md zs-space-right-sm" placeholder="强制顺序" @change="queryList" clearable :teleported="false">
							<el-option v-for="item in sortList" :key="item.id" :label="item.dicName" :value="item.id" />
						</el-select>
						<el-select v-model="queryParams.inspectionStatus" class="zs-select-md zs-space-right-sm" placeholder="配置状态" @change="queryList" clearable :teleported="false">
							<el-option v-for="item in settingList" :key="item.id" :label="item.dicName" :value="item.id" />
						</el-select>
						<el-select v-model="queryParams.effectiveState" class="zs-select-md zs-space-right-sm zs-space-top-sm" placeholder="生效状态" @change="queryList" :teleported="false">
							<el-option v-for="item in dictObj.VALIDATE_FLAG" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue" />
						</el-select>
					</template>
				</el-popover>
				<el-button class="zs-btn-plain" @click="queryList" v-btnPermi="{ permis: ['p_btn_property_inspection_list_query'] }"> 查询 </el-button>
			</span>
			<span>
				<el-button class="zs-btn-md zs-btn-primary" @click="openDrawer(false, 'add', {}, 'base')" v-btnPermi="{ permis: ['p_btn_property_inspection_list_add'], businessFlag: true }">新增</el-button>
			</span>
		</div>

		<!-- teble -->
		<div class="zs-card zs-table-page-content">
			<el-table class="zs-table-page-main" :data="tableData.data" v-loading="tableData.loading" stripe>
				<el-table-column type="index" label="序号" width="60" align="center" :index="index => index + 1 + (tableData.currentPage - 1) * curPageSize" />
				<el-table-column prop="inspectionTypeName" label="巡检类型" minWidth="90" show-overflow-tooltip align="center" :formatter="defaultTableData" />
				<el-table-column prop="routeName" label="路线名称" minWidth="120" show-overflow-tooltip align="left" :formatter="defaultTableData" />
				<el-table-column prop="roleName" label="角色名称" minWidth="120" show-overflow-tooltip align="left" :formatter="defaultTableData" />
				<el-table-column prop="mandatorySequenceName" label="强制顺序" width="90" align="center" :formatter="defaultTableData" />
				<el-table-column prop="triggerTypeTxt" label="触发方式" width="90" align="center" :formatter="defaultTableData" />
				<el-table-column prop="enableStatusName" label="配置状态" minWidth="130" align="center" :formatter="defaultTableData" />
				<el-table-column prop="effectiveState" label="生效状态" width="120" align="center">
					<template #default="{ row }">
						<span :class="row.effectiveState == 1 ? 'zs-validata-status-yes' : 'zs-validata-status-no'">{{ row.effectiveState == 1 ? '有效' : '失效' }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="" label="定义" width="120" align="center">
					<template #default="{ row }">
						<el-button class="zs-link" link size="small" @click="openDrawer(true, 'info', row, 'base')" v-btnPermi="{ permis: ['p_btn_property_inspection_list_view'] }">查看</el-button>
						<el-divider direction="vertical" />
						<el-button class="zs-link" link size="small" @click="openDrawer(false, 'edit', row, 'base')" v-btnPermi="{ permis: ['p_btn_property_inspection_list_edit'], businessFlag: true }">编辑</el-button>
					</template>
				</el-table-column>
				<el-table-column prop="" label="点位" width="220" align="center">
					<template #default="{ row }">
						<el-button class="zs-link" link size="small" @click="openDrawer(true, 'info', row, 'point')" v-btnPermi="{ permis: ['p_btn_property_inspection_list_point_query'] }">查看</el-button>
						<el-divider direction="vertical" />
						<el-button class="zs-link" link size="small" @click="openDrawer(false, 'edit', row, 'point')" v-btnPermi="{ permis: ['p_btn_property_inspection_list_point_edit'], businessFlag: true }">配置</el-button>
						<el-divider direction="vertical" />
						<el-button class="zs-link" link size="small" @click="openDrawer(false, 'edit', row, 'sort')" :disabled="row.pointFlag ? false : true" v-btnPermi="{ permis: ['p_btn_property_inspection_list_point_order'], businessFlag: true }">排序</el-button>
						<el-divider direction="vertical" />
						<el-button class="zs-link" link size="small" @click="openDrawer(false, 'edit', row, 'standard')" :disabled="row.pointFlag ? false : true">标准</el-button>
					</template>
				</el-table-column>
				<el-table-column prop="" label="计划" width="120" align="center">
					<template #default="{ row }">
						<el-button class="zs-link" link size="small" @click="setRow(row, true)" :disabled="row.planFlag ? false : true" v-btnPermi="{ permis: ['p_btn_property_inspection_list_plan_query'] }">查看</el-button>
						<el-divider direction="vertical" />
						<el-button class="zs-link" link size="small" @click="setRow(row, false)" :disabled="row.planFlag ? false : true" v-btnPermi="{ permis: ['p_btn_property_inspection_list_plan_edit'], businessFlag: true }">配置</el-button>
					</template>
				</el-table-column>
			</el-table>
			<div class="zs-space-top-sm zs-table-page-pagination">
				<el-pagination v-model:currentPage="tableData.currentPage" v-model:page-size="curPageSize" :page-sizes="curPageSizes" :small="true" :background="true" layout="total, sizes, prev, pager, next, jumper" :total="tableData.total" @size-change="pageChange('size', $event)" @current-change="pageChange('page', $event)" />
			</div>
		</div>
	</div>

	<!-- 定义抽屉 -->
	<DrawerPlan :isShow="drawer.base.isShowDrawer" :sortList="sortList" :standradTypeList="standradTypeList" :isReadOnly="drawer.base.isReadOnly" :handleType="drawer.base.handleType" :currentRow="currentRow.data" @close="closeDrawer($event, 'base')"> </DrawerPlan>

	<!-- 点位抽屉 -->
	<DrawerPlanPoint :isShow="drawer.point.isShowDrawer" :isReadOnly="drawer.point.isReadOnly" :handleType="drawer.point.handleType" :currentRow="currentRow.data" @close="closeDrawer($event, 'point')"> </DrawerPlanPoint>

	<!-- 点位排序 -->
	<DrawerPlanPointSort :isShow="drawer.sort.isShowDrawer" :isReadOnly="drawer.sort.isReadOnly" :handleType="drawer.sort.handleType" :currentRow="currentRow.data" @close="closeDrawer($event, 'sort')"> </DrawerPlanPointSort>

	<!-- 计划 -->
	<SetPlanDialog ref="plan" @queryList="queryList" @saveCb="planBind"></SetPlanDialog>

	<!-- 标准 -->
	<DrawerPointStandard :isShow="drawer.standard.isShowDrawer" :isReadOnly="drawer.standard.isReadOnly" :standradTypeList="standradTypeList" :handleType="drawer.standard.handleType" :currentRow="currentRow.data" @close="closeDrawer($event, 'standard')"> </DrawerPointStandard>
</template>

<script setup>
	import DrawerPlan from './components/drawerPlan.vue';
	import DrawerPlanPoint from './components/drawerPlanPoint.vue';
	import SetPlanDialog from '@/components/drawerPlan.vue';
	import DrawerPlanPointSort from './components/drawerPlanPointSort.vue';
	import DrawerPointStandard from './components/drawerPointStandard.vue';
	import { planListApi, planProcessDropApi, planBindCbApi, planRoleDropApi } from '@/api/inspect.js';
	import { getDictoryApi } from '@/api/common.js';
	import { ref, reactive } from 'vue';
	import { useStore } from 'vuex';
	import { useRoute } from 'vue-router';
	import { defaultTableData } from '@/utils/publicUtils';

	const route = useRoute();
	let store = useStore();
	const curPageSizes = ref(store.state.uiPageSizes);
	const curPageSize = ref(store.state.uiPageSizeDefault);
	const projectName = ref(decodeURI(route.query.projectName || ""));

	let dictObj = store.getters.getDictObj(['VALIDATE_FLAG']);

	const circularUnit = ref([
		{ name: '按天', value: '0' },
		{ name: '按周', value: '1' },
		{ name: '按月', value: '2' },
		{ name: '按年', value: '3' },
	]);

	// 列表 filed
	let tableData = reactive({
		currentPage: 1,
		total: 0,
		loading: false,
		data: [],
	});

	//查询条件
	let queryParams = reactive({ projectCode: route.query.projectCode, pageNumber: 1, pageSize: curPageSize.value, inventoryName: '', effectiveState: '1' });

	// 抽屉相关
	let currentRow = reactive({ data: {} });
	let drawer = reactive({
		base: {
			handleType: '',
			isReadOnly: false,
			isShowDrawer: false,
		},
		point: {
			handleType: '',
			isReadOnly: false,
			isShowDrawer: false,
		},
		sort: {
			handleType: '',
			isReadOnly: false,
			isShowDrawer: false,
		},
		standard: {
			handleType: '',
			isReadOnly: false,
			isShowDrawer: false,
		},
	});

	const openDrawer = (flag, handleType, row, drawerType) => {
		drawer[drawerType].isReadOnly = flag;
		drawer[drawerType].isShowDrawer = true;
		drawer[drawerType].handleType = handleType;
		currentRow.data = row;
	};

	const closeDrawer = (data, drawerType) => {
		drawer[drawerType].isShowDrawer = data.isShow;
		data.isRefresh && queryList('init');
	};

	// 列表数据源
	const queryList = async init => {
		if (process.env.NODE_ENV !== 'development') {
			let portalResourceList = JSON.parse(localStorage.getItem('portalResourceList'));
			if (init != 'init' && !portalResourceList.includes('p_btn_property_inspection_list_query')) return;
		}
		tableData.loading = true;
		let res = await planListApi(queryParams);
		if (res.data.code !== 200) return;
		initData(res.data.data.list);
		tableData.data = res.data.data.list || [];
		tableData.total = res.data.data.total || 0;
		tableData.loading = false;
	};

	const initData = list => {
		list.forEach(item => {
			let target = circularUnit.value.find(unit => unit.value == item.cycleDayRule);
			item.triggerTypeTxt = item.triggerType == 1 ? '固定时间' : target?.name || '-';
		});
	};

	// 分页
	const pageChange = (type, size) => {
		if (type == 'size') {
			queryParams.pageSize = size;
		} else {
			queryParams.pageNumber = size;
		}
		queryList('init');
	};

	//流程列表
	let processList = ref([]);
	const getProcessList = async () => {
		let res = await planProcessDropApi({ projectCode: route.query.projectCode });
		if (res.data.code !== 200) return;
		res.data.data.forEach(item => {
			item.optionName = `${item.name}（${item.processKey}）`;
		});
		processList.value = res.data.data || [];
	};

	//流程列表
	let roleList = ref([]);
	const getRoleList = async () => {
		let res = await planRoleDropApi();
		if (res.data.code !== 200) return;
		roleList.value = res.data.data || [];
	};

	// 字典
	let standradTypeList = ref([]);
	let sortList = ref([]);
	let settingList = ref([]);
	const getDictory = async () => {
		let res = await getDictoryApi({ sort: true, delFalg: 0 });
		if (res.data.code !== 200) return;
		standradTypeList.value = res.data.data.INSPECTION_TYPE || [];
		sortList.value = res.data.data.MANDATORY_SEQUENCE_TYPE || [];
		settingList.value = res.data.data.INSPECTION_STATUS_TYPE || [];
	};

	//计划相关
	const plan = ref();
	const setRow = (row, planReadonly) => {
		currentRow.data = row;
		plan.value.setRow(row, planReadonly);
	};

	//配置计划后的回调
	const planBind = async () => {
		await planBindCbApi({ id: currentRow.data.id });
		queryList();
	};

	getDictory();
	getProcessList();
	getRoleList();
	queryList('init');
</script>
